﻿#include "messagetableview.h"
#include "user.h"

MessageTableView::MessageTableView(QWidget *parent) : MyTableView(parent)
{
    setModel(&model);

    setEditTriggers(QAbstractItemView::NoEditTriggers);

    connect(&model, &MessageStandardItemModel::updateTotalValue,
            [=](double totalTicket, double totalMoney)
    {
        emit this->updateTotalValue(totalTicket, totalMoney);
    });
}

void MessageTableView::initHiddenState(){
    initMultiHiddenStateList();
}

void MessageTableView::setListPushButton(MultiListPushButton *listPushButton){
    setMultiListPushButton(listPushButton);
    addMultiMenu("message/client", model.headerClient);
    addMultiMenu("message/giver", model.headerGiver);
}

void MessageTableView::setData(QList<Message*> messages){
    this->messages = messages;
}

void MessageTableView::showData(
        UserRelation *queryRelation,
        int type){
    model.setType(type);
    clear();
    QList<Message*> results;
    for(Message *message:messages){
        message->isSend = User::getUsername() == message->sourceUsername;
        int tempType;
        if(message->isSend){
            tempType = type;
        }else{
            tempType = type==1?2:1;
        }
        if(message->type >= 10){
            continue;
        }
        if(message->relationType == tempType || message->relationType>2){
            UserRelation *relation = message->getUserRelation();
            if(relation != nullptr){
                if(queryRelation == nullptr || relation->targetUsername == queryRelation->targetUsername){
                    results.append(message);
                }
            }else{
                results.append(message);
            }
        }
    }

    insertMessage(results);
}

void MessageTableView::clear(){
    model.reset();
    refreshHiddenState();
}

void MessageTableView::insertMessage(Message &message){
    model.insertMessage(message);
}

void MessageTableView::insertMessage(QList<Message*> messages){
    model.insertMessage(messages);
}
